package com.hjx.movie.core.security.controller;



import com.hjx.movie.core.security.auth.JwtAuthService;
import com.hjx.movie.common.utils.LoginType;
import com.hjx.movie.common.utils.Result;
import com.hjx.movie.common.utils.ResultType;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.Map;

/**
 * <p>Title:</p>
 * <p>Description:</p>
 *
 * @author hjx
 * @date 2020/6/10 - 9:02
 */
@Slf4j
@RestController
@RequestMapping("/auth")
public class JwtAuthController {
    @Resource
    JwtAuthService jwtAuthService;

    @PostMapping("/testApi")
    public Result test() {
        return Result.success();
    }

    @PostMapping(value = "/login")
    public Result login(@RequestBody Map<String, String> map) {
        String username = "";
        String password = "";
        String clientLoginType = map.get("loginType");
        Integer loginType =StringUtils.isBlank(clientLoginType)? LoginType.USERNAME_LOGIN.getTypeCode(): LoginType.checkLoginType(clientLoginType);

        switch (loginType){
            case 1:
                username = map.get("username");
                password = map.get("password");
                if (StringUtils.isBlank(username) || StringUtils.isBlank(password)) {
                    return Result.error(ResultType.USER_INPUT_ERROR,"用户名或者密码为空");
                }
                break;
            case 2:
                username = map.get("email");
                password = map.get("captcha");
                log.debug("{}.{}",username,password);
                if (StringUtils.isBlank(username) || StringUtils.isBlank(password)) {
                    return Result.error(ResultType.USER_INPUT_ERROR,"邮箱或者验证码为空");
                }
                break;
        }
        try {
            //成功则将JWT认证结果返回
            String token = jwtAuthService.login(username, password,loginType);
            return Result.success(token);
        } catch (AuthenticationException e) {
            //失败则返回错误信息
            log.error(e.getMessage());
            if (e instanceof UsernameNotFoundException) {
                return Result.error(ResultType.USER_INPUT_ERROR, e.getMessage());
            }
           return Result.error(ResultType.USER_INPUT_ERROR,"用户名或密码错误");
        }
    }

    @PostMapping("/fastLogin")
    public Result fastLogin(@RequestBody Map<String, String> map){
        String email = map.get("email");
        String captcha = map.get("captcha");
        log.debug("{}.{}",email,captcha);
        if (StringUtils.isBlank(email) || StringUtils.isBlank(captcha)) {
            return Result.error(ResultType.USER_INPUT_ERROR,"邮箱或者验证码为空");
        }
        if (!email.matches("^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$")){
            return Result.error(ResultType.USER_INPUT_ERROR,"邮箱格式不正确");
        }
        String token = jwtAuthService.fastRegisterAndLogin(email,captcha);
        return Result.success(token);
    }

    @RequestMapping("/logout")
    public Result logout() {
        String username = SecurityContextHolder.getContext().getAuthentication().getName();
        if (jwtAuthService.logout(username)) {
            log.info("用户{}登出成功",username);
            return Result.success();
        }
        return Result.error(ResultType.SYSTEM_ERROR);
    }

    @RequestMapping("/checkToken")
    public Result checkToken(@RequestHeader("${auth0.header}") String token){
        if (jwtAuthService.checkToken(token)){
            return Result.success();
        }
        return Result.error(ResultType.TOKEN_ERROR,"Token已失效");
    }


    @RequestMapping("/refreshToken")
    public Result refresh(@RequestHeader("${auth0.header}") String token) {
        String refreshToken = jwtAuthService.refreshToken(token);
        if (refreshToken != null) {
            // 返回新token
            return Result.success(refreshToken);
        }
        return Result.error(ResultType.TOKEN_ERROR,"Token已过期");
    }
}
